package models

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"store/bootstrap"
	"store/bootstrap/global"
	"time"
)

var (
	Orm *gorm.DB
)

func Start() {
	if bootstrap.Config.Db.Dsn == "" {
		return
	}

	var err error
	Orm, err = getOrmByDbConfig(bootstrap.Config.Db)
	if err != nil {
		panic(err.Error())
	}
}

func getOrmByDbConfig(config global.Db) (*gorm.DB, error) {
	orm, err := gorm.Open(config.Driver, config.Dsn)
	if err != nil {
		return orm, err
	}

	db := orm.DB()
	db.SetMaxOpenConns(config.MaxConnection)
	db.SetMaxIdleConns(config.MaxIdle)
	db.SetConnMaxLifetime(time.Second * time.Duration(config.MaxLifetime))

	return orm, nil
}
